package filter

import "strings"

type KeywordsSQL struct {
	Keywords []string
	And      []string //And Keywords
	Or       []string //Or Keywords
}

func SearchKeywords(s string) KeywordsSQL {
	s = String(s)
	s = strings.Trim(s, "+")
	val := KeywordsSQL{}
	if strings.Contains(s, "+") {
		for i := 0; i < 50; i++ {
			if strings.Contains(s, "++") {
				s = strings.ReplaceAll(s, "++", "+")
			} else {
				break
			}
		}
		for _, v := range strings.Split(s, "+") {
			vr := v
			if vr[0] != '"' {
				vr = "\"" + vr
			}
			if vr[len(vr)-1] != '"' {
				vr = vr + "\""
			}
			if v != vr {
				s = strings.ReplaceAll(s, v, vr)
			}
		}
		s = strings.ReplaceAll(s, "+", " ")
	}
	for _, vs := range strings.Split(s, " ") {
		if vs == "" || vs == "%" || vs == "%%" {
			continue
		}
		kw := parseLikeSQL(vs)
		if kw == "" || kw == "%" || kw == "%%" {
			continue
		}
		val.Keywords = append(val.Keywords, strings.Trim(vs, "\""))
		if vs[0] == '"' && vs[len(vs)-1] == '"' {
			val.And = append(val.And, kw)
		} else {
			val.Or = append(val.Or, kw)
		}
	}
	return val
}

func parseLikeSQL(s string) string {
	s = strings.ReplaceAll(s, "`", "")
	s = strings.ReplaceAll(s, "'", "")
	s = strings.Trim(s, "%")
	s = strings.Trim(s, "\"")
	for i := 0; i < 50; i++ {
		if strings.Contains(s, "%%") {
			s = strings.ReplaceAll(s, "%%", "%")
		} else {
			break
		}
	}
	for i := 0; i < 50; i++ {
		if strings.Contains(s, "\"\"") {
			s = strings.ReplaceAll(s, "\"\"", "\"")
		} else {
			break
		}
	}
	s = "%" + s + "%"
	return s
}
